package mapper

import (
	"github.com/beego/beego/v2/client/orm"
	"ksd-social-api/commons/page"
	"ksd-social-api/modules/msg/model"
	"time"
)

type MessageSystemMapper struct {
}

/**
 * 保存系统消息
 * @author feige
 * @date 2023-11-03
 * @version 1.0
 * @desc
 */
func (mapper *MessageSystemMapper) SaveMessageSystem(userId uint64, systemId uint64, data *model.MessageSystem) bool {
	data.CreateTime = time.Now()
	_, err := orm.NewOrm().Insert(data)
	if data.Stype == 1 {
		orm.NewOrm().Raw("update xk_msg_ponit set system_lasttime=? where user_id = ? and system_id = ?", data.CreateTime, userId, systemId).Exec()
	}
	if data.Stype == 2 {
		orm.NewOrm().Raw("update xk_msg_ponit set course_lasttime=? where user_id = ? and system_id = ?", data.CreateTime, userId, systemId).Exec()
	}
	return nil == err
}

/**
 * 根据ID删除文章评论消息
 * @author feige
 * @date 2023-11-03
 * @version 1.0
 * @desc
 */
func (mapper *MessageSystemMapper) DelMessageSystemById(id int, systemId uint64) bool {
	// 创建orm对象
	_, err := orm.NewOrm().Raw("delete from xk_msg_system where id = ? and system_id = ?", id, systemId).Exec()
	return err == nil
}

/**
 * @desc 根据ID查询
 * @author feige
 * @date 2023-11-14
 * @version 1.0
 */
func (mapper *MessageSystemMapper) GetMessagSystemById(id int, systemId uint64) (*model.MessageSystem, error) {
	// 获取数据库链接
	mysql := orm.NewOrm()
	// 准备一个切片容器
	var messageSystem model.MessageSystem
	// 执行查询
	err := mysql.Raw("select * from xk_msg_system where  id  = ? and system_id = ?").SetArgs(id, systemId).QueryRow(&messageSystem)
	if err != nil {
		return nil, err
	}
	return &messageSystem, nil
}

/**
 * @author feige
 * @date 2023-10-12
 * @version 1.0
 * @desc 系统消息
 */
func (mapper *MessageSystemMapper) FindMessageSystemPage(stype int, systemId uint64, pageNo int64, pageSize int64) (p *page.Page, err error) {
	// 准备容器对象，开始装载数据库数据
	messageSystemList := []model.MessageSystem{}
	//创建orm对象
	mysql := orm.NewOrm()
	cond := orm.NewCondition()
	// 开始执行sql查询
	qs := mysql.QueryTable("xk_msg_system")
	// 设定两个条件
	cond = cond.And("status", 1).And("system_id", systemId)
	// 设定两个条件
	if stype > 0 {
		cond = cond.And("stype", stype)
	}
	// 执行count查询
	total, err1 := qs.SetCond(cond).Count()
	if err1 != nil {
		return nil, err
	}
	// 重新换算分页和规则
	page := p.Page(pageNo, pageSize, total)
	// 分页查询
	_, err2 := qs.SetCond(cond).OrderBy("-update_time").Limit(page.PageSize, page.CurrentPage).All(&messageSystemList,
		"id",
		"msg",
		"title",
		"url",
		"stype",
		"create_time",
		"update_time",
	)
	// 6：把查询的数据放入到分页的records字段，准备返回
	page.Records = messageSystemList
	// 7: 如果没有找到直接返回
	if err2 != nil {
		return nil, err2
	}
	return page, nil
}
